package com.ld.web.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;

@ServerEndpoint("/socket/websocket")
@Component
public class AllWebSocket {

    private Logger logger = LoggerFactory.getLogger(AllWebSocket.class);

    private static int onlineCount = 0;
    private static CopyOnWriteArrayList<AllWebSocket> webSockets = new CopyOnWriteArrayList<>();
    private Session session;

    //连接建立成功调用的方法
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSockets.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        logger.info("AllWebSocket:有新连接加入！当前在线人数为" + getOnlineCount());
//        try {
//            sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
//        } catch (IOException e) {
//            System.out.println("IO异常");
//        }
    }

    @OnClose
    public void onClose(){

        webSockets.remove(this);
        subOnlineCount();
        System.out.println("AllWebSocket:有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        logger.info("AllWebSocket:client message:"+message);
        sendAll(message);
    }

    private void sendAll(String message){
        String now = getNowTime();
        for (AllWebSocket idno:webSockets) {
            try {
                idno.sendMessage(now+":"+message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        throwable.printStackTrace();
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        AllWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        AllWebSocket.onlineCount--;
    }

    private String getNowTime(){
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }
}
